package com.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.util.ConfigUtil;

import com.util.BODY;
import com.util.Constant;
import com.util.HttpRequest;
import com.util.JSONUtil;
import com.util.MD5;
import com.util.OpenKey;
import com.util.ReadConfig;
import com.util.SessionInfo;

@Controller
@RequestMapping("/DKJSQController")
public class DKJSQController {

	private static final Logger logger = Logger
			.getLogger(DKJSQController.class);
	Map map = new HashMap();
	List list = new ArrayList();
	@RequestMapping("/test")
	@ResponseBody
	public String entryinterface(HttpServletRequest request, HttpServletResponse response ,HttpSession session, String limit ,Double invest,int year,String hkfs) throws IOException{
		SessionInfo sessionIn = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
		//读取配置文件路径
		String interfaceUrl = ReadConfig.readValue();
		Map reqMap = new HashMap();
		OpenKey opk=new OpenKey();
		//接口编码
		reqMap.put("AUTHORITY", "YBGJJ169"); 
		//接口参数
		int month = year * 12;//期限
		String m= month+"";
		reqMap.put("OpenKey",sessionIn.getKEY());
		BODY b=new BODY();
		b.setMonth(m);
		reqMap.put("BODY",b);
		String result=opk.getOpenKey(reqMap, session);
		logger.info("YBGJJ169接口返回内容:"+result);
		
		if(result != null){
			Double mqhk=0.00;
	        double monthRate=0.00;//月利率
	        List list= new ArrayList();
	        Map maptt=new HashMap();
			Map retMap = JSONUtil.toMap(result);
			Map mx=JSONUtil.toMap(JSONUtil.ToJsongString2(retMap.get("body")));
			List retlist = (List)mx.get("RETDATA");
			
			Map lv =(Map) retlist.get(0);
			if(retMap.get("RETURNCODE").equals("100")){
				monthRate=(Double) lv.get("LILV");
				if(monthRate !=0&& monthRate >0){
				if(hkfs.equals("1")){
					/**
					 * 等额本息
					 */
					// 每月本息金额  = (本金×月利率×(1＋月利率)＾还款月数)÷ ((1＋月利率)＾还款月数-1)
			        double monthIncome = (invest* monthRate * Math.pow(1+monthRate,month))/(Math.pow(1+monthRate,month)-1);//金额
			        double monthCapital = 0;
			        double monthInterest = 0;
			        double capital = invest;
			        double tmpCapital = 0;
			        Double hkze=0.0;
			        Double lxze=0.0;
			        for(int i=1;i<month+1;i++){
			        	Map map=new HashMap();
			            monthCapital = (invest* monthRate * (Math.pow((1+monthRate),i-1)))/(Math.pow(1+monthRate,month)-1);//本金  
			            capital = capital - tmpCapital;
			            monthInterest = capital * monthRate; 
			            tmpCapital = (invest* monthRate * (Math.pow((1+monthRate),i-1)))/(Math.pow(1+monthRate,month)-1);//利息
			            map.put("msg", "1");
			            map.put("QC", "第"+i+"期");
			            map.put("CHBX", String.format("%.2f", monthIncome));
			            map.put("CHLX",  String.format("%.2f", monthInterest));
			            map.put("CHBJ",   String.format("%.2f", monthCapital));
			            list.add(i-1, map);
			        }
				}else{
					/**
					 * 等额本金计算方式
					 */
					 Double hkze=0.0;
					 Double lxze=0.0;
					for(int i=0;i<month;i++){
						Map map=new HashMap();
						Double lx=(invest-Double.parseDouble(String.format("%.2f", invest/month))*i)*monthRate;
							map.put("msg", "1");
						    map.put("QC", "第"+(i+1)+"期");
							map.put("CHBX", String.format("%.2f", invest/month+lx));
							map.put("CHLX", String.format("%.2f",lx));
							map.put("CHBJ", String.format("%.2f", invest/month));
							list.add(i, map);
					}
				}
				}else{
					System.out.println("利率没有查到!");
				}
				
				response.setHeader("Content-type", "textml;charset=UTF-8");
				response.setCharacterEncoding("UTF-8");
				String jsonString = JSONUtil.ToJsongString2(list);
				PrintWriter pw = response.getWriter();
				pw.write(jsonString);
			}
		}
		return null;
	}
	@RequestMapping("/syjsq")
	@ResponseBody
	public String sydkjsq(HttpServletRequest request, HttpServletResponse response ,HttpSession session,String DKQX ,String DKJE,String limit ,Double invest,int year,String hkfs) throws IOException{
		SessionInfo sessionIn = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
		//读取配置文件路径
		String interfaceUrl = ReadConfig.readValue();
		Map remap = new HashMap();
		BODY body = new BODY();
		Date date=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		String Key="";
		if(sessionIn!=null){
			if(!(sessionIn.getKEY().equals("")|| sessionIn.getKEY()==null)){
				 Key=sessionIn.getKEY();
			}
		}
		String a="";
		String Timestamp=sdf.format(date);
		String jm=Constant.mima+Timestamp+Constant.miyao;
		// 接口编码
		System.out.println(jm);
		MD5 md5=new MD5();
		a=md5.getMD5(jm).toString();
			body.setPassWd(a);
				remap.put("AUTHORITY", "YBGJJ100");
				// 接口参数
				remap.put("LOGUserName",Constant.username);
				remap.put("BODY", body);
				body.setTimestamp(Timestamp);
				String json3 = JSONUtil.ToJsongString2(remap);
				// 请求
				String result2 = HttpRequest.doPost(interfaceUrl, json3);
				logger.info("接口返回内容:" + result2);
				Map retMap2 = JSONUtil.toMap(result2);
				
					if(retMap2.get("RETURNCODE").equals("100")){
						Map mx2 = JSONUtil.toMap(JSONUtil.ToJsongString2(retMap2.get("body")));
						List jx = (List) mx2.get("RETDATA");
						Map m = (Map) jx.get(0);
						Key += m.get("OpenKey").toString();		
					}else{
						map.put("code", 1);
						map.put("CW", retMap2.get("RETURNDESC").toString());
						list.add(retMap2);
						response.setHeader("Content-type", "text/html;charset=UTF-8");
						response.setCharacterEncoding("UTF-8");
						String jsonString = JSONUtil.ToJsongString2(map);
						PrintWriter pw = response.getWriter();
						pw.write(jsonString);
						return null;
					}
		Map reqMap = new HashMap();
		OpenKey opk=new OpenKey();
		//接口编码
		reqMap.put("AUTHORITY", "YBGJJ246"); 
		//接口参数
		int month = year * 12;//期限
		String m= month+"";
		reqMap.put("OpenKey",Key);
		BODY b=new BODY();
		b.setMonth(m);
		b.setDKQX(m);
		b.setDKJE(DKJE);
		reqMap.put("BODY",b);
		String result=opk.getOpenKey(reqMap, session);
		logger.info("YBGJJ170接口返回内容:"+result);
		Map retMap = JSONUtil.toMap(result);
		if(retMap.get("RETURNCODE").equals("100")){
			map.put("code", 0);
			map.put("msg", "1");
			map.put("data",retMap.get("body"));
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			String jsonString = JSONUtil.ToJsongString2(map);
			PrintWriter pw = response.getWriter();
			pw.write(jsonString);
		}else{
			map.put("code", 1);
			map.put("msg", "1");
			map.put("CW",retMap.get("RETURNDESC"));
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			String jsonString = JSONUtil.ToJsongString2(map);
			PrintWriter pw = response.getWriter();
			pw.write(jsonString);
		}
	return null;
	}
	@RequestMapping("/dkjsq")
	@ResponseBody
	public String dkjsq(HttpServletRequest request, HttpServletResponse response ,HttpSession session, String limit ,Double invest,int year,String hkfs) throws IOException{
		SessionInfo sessionIn = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
		//读取配置文件路径
		String interfaceUrl = ReadConfig.readValue();
		Map remap = new HashMap();
		BODY body = new BODY();
		Date date=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		String Key="";
		if(sessionIn!=null){
			if(!(sessionIn.getKEY().equals("")|| sessionIn.getKEY()==null)){
				 Key=sessionIn.getKEY();
			}
		}
		String a="";
		String Timestamp=sdf.format(date);
		String jm=Constant.mima+Timestamp+Constant.miyao;
		// 接口编码
		System.out.println(jm);
		MD5 md5=new MD5();
		a=md5.getMD5(jm).toString();
			body.setPassWd(a);
				remap.put("AUTHORITY", "YBGJJ100");
				// 接口参数
				remap.put("LOGUserName",Constant.username);
				remap.put("BODY", body);
				body.setTimestamp(Timestamp);
				String json3 = JSONUtil.ToJsongString2(remap);
				// 请求
				String result2 = HttpRequest.doPost(interfaceUrl, json3);
				logger.info("接口返回内容:" + result2);
				Map retMap2 = JSONUtil.toMap(result2);
				
					if(retMap2.get("RETURNCODE").equals("100")){
						Map mx2 = JSONUtil.toMap(JSONUtil.ToJsongString2(retMap2.get("body")));
						List jx = (List) mx2.get("RETDATA");
						Map m = (Map) jx.get(0);
						Key += m.get("OpenKey").toString();		
					}else{
						map.put("code", 1);
						map.put("CW", retMap2.get("RETURNDESC").toString());
						list.add(retMap2);
						response.setHeader("Content-type", "text/html;charset=UTF-8");
						response.setCharacterEncoding("UTF-8");
						String jsonString = JSONUtil.ToJsongString2(map);
						PrintWriter pw = response.getWriter();
						pw.write(jsonString);
						return null;
					}
		Map reqMap = new HashMap();
		OpenKey opk=new OpenKey();
		//接口编码
		reqMap.put("AUTHORITY", "YBGJJ169"); 
		//接口参数
		int month = year * 12;//期限
		String m= month+"";
		reqMap.put("OpenKey",Key);
		BODY b=new BODY();
		b.setMonth(m);
		reqMap.put("BODY",b);
		String result=opk.getOpenKey(reqMap, session);
		logger.info("YBGJJ169接口返回内容:"+result);
		
		if(result != null){
			Double mqhk=0.00;
	        double monthRate=0.00;//月利率
	        List list= new ArrayList();
	        Map maptt=new HashMap();
			Map retMap = JSONUtil.toMap(result);
			Map mx=JSONUtil.toMap(JSONUtil.ToJsongString2(retMap.get("body")));
			List retlist = (List)mx.get("RETDATA");
			
			Map lv =(Map) retlist.get(0);
			if(retMap.get("RETURNCODE").equals("100")){
				monthRate=(Double) lv.get("LILV");
				if(monthRate !=0&& monthRate >0){
				if(hkfs.equals("1")){
					/**
					 * 等额本息
					 */
					// 每月本息金额  = (本金×月利率×(1＋月利率)＾还款月数)÷ ((1＋月利率)＾还款月数-1)
			        double monthIncome = (invest* monthRate * Math.pow(1+monthRate,month))/(Math.pow(1+monthRate,month)-1);//金额
			        double monthCapital = 0;
			        double monthInterest = 0;
			        double capital = invest;
			        double tmpCapital = 0;
			        Double hkze=0.0;
			        Double lxze=0.0;
			        for(int i=1;i<month+1;i++){
			        	Map map=new HashMap();
			            monthCapital = (invest* monthRate * (Math.pow((1+monthRate),i-1)))/(Math.pow(1+monthRate,month)-1);//本金  
			            capital = capital - tmpCapital;
			            monthInterest = capital * monthRate; 
			            tmpCapital = (invest* monthRate * (Math.pow((1+monthRate),i-1)))/(Math.pow(1+monthRate,month)-1);//利息
			            map.put("msg", "1");
			            map.put("QC", "第"+i+"期");
			            map.put("CHBX", String.format("%.2f", monthIncome));
			            map.put("CHLX",  String.format("%.2f", monthInterest));
			            map.put("CHBJ",   String.format("%.2f", monthCapital));
			            list.add(i-1, map);
			        }
				}else{
					/**
					 * 等额本金计算方式
					 */
					 Double hkze=0.0;
					 Double lxze=0.0;
					for(int i=0;i<month;i++){
						Map map=new HashMap();
						Double lx=(invest-Double.parseDouble(String.format("%.2f", invest/month))*i)*monthRate;
							map.put("msg", "1");
						    map.put("QC", "第"+(i+1)+"期");
							map.put("CHBX", String.format("%.2f", invest/month+lx));
							map.put("CHLX", String.format("%.2f",lx));
							map.put("CHBJ", String.format("%.2f", invest/month));
							list.add(i, map);
					}
				}
				}else{
					System.out.println("利率没有查到!");
				}
				
				response.setHeader("Content-type", "textml;charset=UTF-8");
				response.setCharacterEncoding("UTF-8");
				String jsonString = JSONUtil.ToJsongString2(list);
				PrintWriter pw = response.getWriter();
				pw.write(jsonString);
			}
		}
		return null;
	}
}
